package com.Drools.其他;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ClassLoaderExample {

    public static void main(String[] args) {
        try {
            // 加载class文件
            byte[] classData = loadClassData("path/****.class");

            // 使用自定义类加载器加载class文件
            Class<?> clazz = new CustomClassLoader().defineClass(classData);

            // 实例化对象
            Object obj = clazz.getDeclaredConstructor().newInstance();

            // 调用方法
            Method method = clazz.getMethod("methodName");
            method.invoke(obj);
        } catch (IOException | NoSuchMethodException | InstantiationException |
                 IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    private static byte[] loadClassData(String className) throws IOException {
        File file = new File(className);
        FileInputStream fis = new FileInputStream(file);
        byte[] data = new byte[(int) file.length()];
        fis.read(data);
        fis.close();
        return data;
    }
}

class CustomClassLoader extends ClassLoader {
    public Class<?> defineClass(byte[] classData) throws ClassFormatError {
        return defineClass(null, classData, 0, classData.length);
    }
}